# !/usr/bin/env python
# encoding: utf-8


"""
  @author: gaogao
  @file: check_equip_comm_thread.py
  @time: 2022/7/31 17:04
  @desc:
"""
import random
from re import T
import pyvisa as visa
from PyQt5.QtCore import QObject, pyqtSignal, QThread
import time
from utils.log_util import loggings
from ATS.util.calcu_step_util import get_step_list,get_points_list
from ATS.application.LCR_App.U2722A_App import U2722A_App
from utils.auto_range import auto_range


class IdarkRepeatabilityTask(QObject):
    result_signal = pyqtSignal(object, object)
    finished_signal = pyqtSignal()

    def __init__(self, duration, frequency):
        super().__init__()
        self.duration = int(duration) * 60
        self.frequency = int(frequency)
        self.interval = int(self.duration / self.frequency)
        self.U2722_inst = U2722A_App("SMU4")
        self.flag = True

    def run(self):
        QThread.sleep(5)
        if self.interval > 0:
            for _ in range(self.frequency):
                if self.flag:
                    voltage_list, current_list = self.get_dark_current_result()
                    self.result_signal.emit(voltage_list, current_list)
                    QThread.sleep(self.interval)
                else:
                    break
            self.finished_signal.emit()
        else:
            voltage_list, current_list = self.get_dark_current_result()
            self.result_signal.emit(voltage_list, current_list)
            self.finished_signal.emit()

    def get_dark_current_result(self):
        voltage_list = get_points_list(-3,0.5,71)
        current_list = []
        self.U2722_inst.set_voltage(0,1)
        self.U2722_inst.set_voltage_range(1)
        self.U2722_inst.set_voltage_range(2)
        self.U2722_inst.set_current_range_limit("120mA",0.12,1)
        self.U2722_inst.set_current_range_limit("1mA",0.001,2)
        actual_range = "1mA"
        self.U2722_inst.output_state(1,1)
        self.U2722_inst.output_state(1,2)

        for voltage in voltage_list:
            self.U2722_inst.set_voltage(voltage, 2)
            current = self.U2722_inst.get_current_value(2)
            current_list.append(abs(float(current)))
            is_variety, current_range, limit = auto_range(current, actual_range)
            if is_variety:
                actual_range = current_range
                self.U2722_inst.set_current_range_limit(actual_range, limit,2)
                self.U2722_inst.set_voltage(voltage, 2)
                current = self.U2722_inst.get_current_value(2)
                current_list[-1] = abs(float(current))

        return voltage_list,current_list
